package com.pitop.base.ctrl;

import com.opensso.sdk.tools.SessionTools;
import com.pitop.account.entity.Account;
import com.pitop.account.vo.AccountVO;
import com.pitop.core.enums.SessionEnum;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.StringTools;
import com.pitop.core.tools.redis.RedisUtils;
import com.pitop.setting.entity.Setting;
import com.pitop.setting.service.SettingSVImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by jiyan on 2019/4/2.
 */
@RestController
@RequestMapping("/base")
@Slf4j
@Api(value = "基本控制器", description = "基本控制器")
public class BaseCtrl {

    @Autowired
    private SettingSVImpl settingSVImpl;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 获取登录信息
     *
     * @return BeanRet
     */
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @GetMapping(value = "/loadAccount")
    @ResponseBody
    public Account loadAccount(HttpServletRequest request) {
        //1.获取token
        String authorization = request.getHeader(SessionEnum.authorization.name());
        if (StringUtils.isBlank(authorization)) {
            throw new BaseException(BaseException.BaseExceptionEnum.Session_Error);
        }
        String sso_secret = settingSVImpl.loadByK(Setting.Key.Token_Secret.name()).getV();
        String accountStr = com.pitop.core.tools.JwtToken.getTokenValue(authorization, sso_secret, SessionEnum.Account.name());
        //2.获取用户信息
        String sessionKey = SessionTools.Instance.genSessionKey(accountStr);
        AccountVO accountVO = (AccountVO)redisUtils.get(sessionKey);
        if(accountVO == null) {
            throw new BaseException(BaseException.BaseExceptionEnum.Session_Error);
        }
        Account account = StringTools.convertObject(accountVO, Account.class);
        return account;
    }
}
